// pages/bluetooth/bluetooth.js

var tmsdk = require('../../sdk/DoormasterSDK-V1.3.js');
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    deviceId: '' //2841655459 df:21:09:91:d4:5c
  },

  //扫描蓝牙设备
  scanDevices: function () {
    var that = this;
    tmsdk.scanDevices(function (res) {
      console.log('ret:', res);
      if (!res.isBluetoothAvailable){
        wx.showModal({
          title: 'Caution',
          content: '请打开蓝牙',
        })
        return;
      }

      var scanList = res.scanList;
      for (let i = 0; i < scanList.length; i++) {
        if (scanList[i].name == 'XM-0159526086') { //视具体设备处理
          that.setData({
            deviceId: scanList[i].deviceId
          });
        }
      }
    });
  },

  // 执行开门操作
  openDoor: function (event) {
    console.log('++++event:', event)
    var deviceId = event.currentTarget.dataset.deviceid;
    var sendData = 'AC0105885a027f7eb76c16e67bbadc21501993'; //调用门管家接口动态获取
    console.log('deviceId:', deviceId);
    tmsdk.openDoor(deviceId, sendData, function (res) {
      if (res.errCode === 0) {
        wx.showToast({
          title: '开门成功',
          icon: "success",
        });
      }
      else {
        wx.showToast({
          title: '开门失败,' + '错误码：' + res.errCode,
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //监听蓝牙适配器状态变化
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log(`adapterState changed, now is`, res)
    });

    this.scanDevices();
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    //注意！下拉刷新，Android系统设备应执行一次停止蓝牙发现接口
	if (app.globalData.platform == 'android') {
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log('stopBluetoothDevicesDiscovery', res)
        },
      });
    }
    //重新扫描蓝牙设备
    this.scanDevices();
  },

  onUnload: function(){
    wx.stopBluetoothDevicesDiscovery({
      success: function(res) {
        console.log('---stopBluetoothDevicesDiscovery--success',res);
      },
    });

    wx.closeBluetoothAdapter({
      success: function(res) {
        console.log('---closeBluetoothAdapter--success', res);
      },
    });
  }
})